
export default class Memo<T> {
    private memoValue: T | undefined
    private factory: () => T
    private dependencies: any[] | undefined

    constructor(factory: () => T) {
        this.factory = factory
    }

    get(dependencies: any[]): T {
        let depCheckFlag = true

        if (this.dependencies === undefined) {
            depCheckFlag = false
            this.dependencies = dependencies
        }

        if (this.memoValue === undefined) {
            this.memoValue = this.factory()
            this.dependencies = dependencies
            
            return this.memoValue
        }

        if (depCheckFlag) {
            if (this.dependencies.length != dependencies.length) {
                this.memoValue = this.factory()
            } else {
                for (let i = 0; i < dependencies.length; ++i) {
                    if (!Object.is(dependencies[i], this.dependencies[i])) {
                        this.dependencies = dependencies

                        this.memoValue = this.factory()
                    }
                }
            }
        }

        return this.memoValue
    }
}
